package com.thinkingcoder.common.util;

import com.thinkingcoder.common.http.HttpProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.thinkingcoder.common.http.OkHttpInvoker;

import lombok.SneakyThrows;

/**
 * interface for http invoke.
 */
public interface HttpUtils {

    Logger log = LoggerFactory.getLogger(HttpUtils.class);

    String get(String url);

    String post(String url, String body);

    HttpUtils DEFAULT = new OkHttpInvoker(new HttpProperties());

    @SneakyThrows
    static <T> T httpGet(String url, Class<T> clazz) {
        log.debug("httpGet ===> url : {} , clazz : {}", url, clazz);
        String responseJson = DEFAULT.get(url);
        log.debug("httpGet ===> responseJson : {}", responseJson);
        return JSON.parseObject(responseJson, clazz);
    }

    @SneakyThrows
    static <T> T httpGet(String url, TypeReference<T> typeReference) {
        log.debug("httpGet ===> url : {} , typeReference : {}", url, typeReference);
        String responseJson = DEFAULT.get(url);
        log.debug("httpGet ===> responseJson : {}", responseJson);
        return JSON.parseObject(responseJson, typeReference);
    }

    @SneakyThrows
    static <T> T httpPost(String url, String body, Class<T> clazz) {
        log.debug("httpPost ===> url : {} , body : {} , clazz : {}", url, body, clazz);
        String responseJson = DEFAULT.post(url, body);
        log.debug("httpPost ===> responseJson : {}", responseJson);
        return JSON.parseObject(responseJson, clazz);
    }

    @SneakyThrows
    static <T> T httpPost(String url, String body, TypeReference<T> typeReference) {
        log.debug("httpPost ===> url : {} , body : {} , typeReference : {}", url, body, typeReference);
        String responseJson = DEFAULT.post(url, body);
        log.debug("httpPost ===> responseJson : {}", responseJson);
        return JSON.parseObject(responseJson, typeReference);
    }

}
